package com.demo.shop.action;

import com.demo.shop.bean.User;
import com.demo.shop.service.ShopService;
import com.demo.shop.utils.Constants;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private HttpServletRequest request;
    private HttpServletResponse response;
    // 定义业务层对象
    private ShopService shopService;

    @Override
    public void init() throws ServletException {
        super.init();
        // 获取 Spring 的容器，然后从容器中得到业务层对象
        ServletContext servletContext = getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        shopService = (ShopService) context.getBean("shopService");
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        // super.service(req, res);
        this.request = req;
        this.response = res;

        String method = req.getParameter("method");
        switch (method) {
            case "getJsp":
                req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, res);
                break;
            case "login":
                login();
                break;
        }
    }

    private void login() {
        try {
            String loginName = request.getParameter("loginName");
            String password = request.getParameter("password");
            Map<String, Object> results = shopService.login(loginName, password);
            if ((int) results.get("code") == 0) {
                // 登录成功
                // 把登陆成功的用户注入到session会话中去
                // 跳转到主界面
                User user = (User) results.get("msg");
                request.setAttribute(Constants.USER_SESSION, user);
                // 请求跳转到主界面的 servlet
                response.sendRedirect(request.getContextPath() + "/list?method=getAll");
            } else {
                String msg = (String) results.get("msg");
                request.setAttribute("msg", msg);
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
